 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=77 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Data exception wrapping
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='DAOException,exception chain,exception chaining,IOException,JDBC,MyMessageDAO,MyMessageDAOSql,SQLException,SqlFetcher,wrapper,database,exception,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Data exception wrapping</div>

<div class='main-body'>
 
<br>Data can be stored in various ways, for example:
<ul>
<li>
a relational database</li>

<li>
text files</li>

<li>
on the web (for example, fetching the weather forecast from a web site)</li>
</ul>
If the storage method changes, then the low level <tt>Exception</tt> objects
thrown by the data access layer can also change. For example, when the
data store is moved from text files to a relational database, <tt>IOException</tt>
is replaced with <tt>SQLException.</tt>
<p>In order to prevent such a change from propagating to higher layers,
one can wrap such low level <tt>Exception</tt>s in a generic "data exception"
wrapper, designed exclusively to protect the higher layers from such changes.

<P><tt>Throwable.<a href='http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Throwable.html#getCause()'>getCause()</a></tt>
can always be used to extract the original exception, if desired.

<p><b>Example</b>

<p>When building applications with the WEB4J tool, <tt>DAOException</tt> 
is the only checked exception that should be emitted by an application's data access layer.
All occurrences of checked exceptions are either handled within the data layer, 
or, if they are thrown, translated into a <tt>DAOException</tt>.

<p>In the following example, <tt>ConnectionSrc</tt> encapulates how an application
creates or accesses <tt>Connection</tt>s. When an <tt>SQLException</tt>
or a <tt>NamingException</tt> occurs in its implementation, it is
always wrapped in a <tt>DAOException</tt>, and then re-thrown to the caller.

<P>This example is particulary appropriate because of the <tt>NamingException</tt>. 
If the <tt>NamingException</tt> was <em>not</em> translated into an <tt>DAOException</tt>, 
and thrown as is, then it would be visible <em>directly</em> to the caller. That is, the caller would 
know that the data layer is implemented using JNDI - which is likely inappropriate.
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.util.logging.*;
<span class='keyword'>import</span> java.sql.Connection;
<span class='keyword'>import</span> java.sql.SQLException;

<span class='keyword'>import</span> javax.naming.Context;
<span class='keyword'>import</span> javax.naming.InitialContext;
<span class='keyword'>import</span> javax.naming.NamingException;
<span class='keyword'>import</span> javax.sql.DataSource;
<span class='keyword'>import</span> hirondelle.web4j.database.DAOException;
<span class='keyword'>import</span> hirondelle.web4j.database.ConnectionSource;
<span class='keyword'>import</span> hirondelle.web4j.util.Util;

<span class='comment'>/** 
* Fetch a &lt;tt&gt;Connection&lt;/tt&gt; from a pool managed by the container.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ConnectionSrc <span class='keyword'>implements</span> ConnectionSource  {

  <span class='comment'>//..elided
</span>  
  <span class='keyword'>private</span> Connection getConnectionByName(String aDbName) <span class='keyword'>throws</span> DAOException {
    Connection result = <span class='keyword'>null</span>;
    String dbConnString = (String)MAP_NAME_TO_CONN_STRING.get(aDbName);  
    <span class='keyword'>if</span>( ! Util.textHasContent(dbConnString) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Unknown db name : "</span> + Util.quote(aDbName));
    }
    <span class='keyword'>try</span> {
      Context initialContext = <span class='keyword'>new</span> InitialContext();
      <span class='keyword'>if</span> ( initialContext == <span class='keyword'>null</span> ) {
        fLogger.severe(<span class='literal'>"InitialContext is null. Db : "</span> + Util.quote(dbConnString));
      }
      DataSource datasource = (DataSource)initialContext.lookup(dbConnString);
      <span class='keyword'>if</span> ( datasource == <span class='keyword'>null</span> ){
        fLogger.severe(<span class='literal'>"Datasource is null for : "</span> + dbConnString);
      }
      result = datasource.getConnection();
    }
    <span class='keyword'>catch</span> (NamingException ex){
      <span class='comment'>//EXCEPTION WRAPPING
</span>      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(
        <span class='literal'>"Config error with JNDI and datasource, for db "</span> + Util.quote(dbConnString), ex
      );
    }
    <span class='keyword'>catch</span> (SQLException ex ){
      <span class='comment'>//EXCEPTION WRAPPING
</span>      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(
       <span class='literal'>"Cannot get connection from datasource, for db "</span> + Util.quote(dbConnString), ex
      );
    }
    <span class='keyword'>return</span> result;
  }
}
   
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction564b-2.html?Id=66'>Data access objects</a> <br>
 
  
  <a href='TopicAction0d22-2.html?Id=76'>Reduce database code duplication</a> <br>
 
  
  <a href='TopicAction62d0-2.html?Id=120'>Exception translation</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
  
  <a href='TopicAction5ee8-2.html?Id=235'>Beware of unknown root causes</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='77'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=77 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
